package fetcher

import (
	"bufio"
	"bytes"
	"fmt"
	grpcError "gc-rds-ha/internal/error"
	"io"
	"net/http"
	"time"

	"google.golang.org/grpc/status"

	log "github.com/sirupsen/logrus"
)

type FetchParams struct {
	Method      string
	Url         string
	Data        []byte
	ContentType string
}

// HttpRequest 发起http请求，目前只支持get和post
func (p *FetchParams) HttpRequest() ([]byte, error) {
	log.Infof("Fetching url %s", p.Url)
	var (
		err  error
		b    []byte
		resp = &http.Response{}
	)

	switch p.Method {
	case "get":
		client := &http.Client{
			Timeout: time.Second * 120, // 设置超时时间为 120 秒
		}
		req, err := http.NewRequest("GET", p.Url, nil)
		if err != nil {
			fmt.Println("Error creating request:", err)
			return b, err
		}
		resp, err = client.Do(req)
		if err != nil {
			fmt.Println("Error making request:", err)
			return b, err
		}
	case "post":
		resp, err = http.Post(p.Url, p.ContentType, bytes.NewBuffer(p.Data))
	default:
		return b, status.Errorf(grpcError.ErrArgsInvalid, "不支持方法: %s", p.Method)
	}
	if err != nil {
		log.WithField("http.Get wrong", log.Fields{"err:": err}).Error()
		return b, err
	}

	defer resp.Body.Close()
	bodyReader := bufio.NewReader(resp.Body)

	all, err := io.ReadAll(bodyReader)
	if err != nil {
		log.WithFields(log.Fields{"err:": err}).Error("io.ReadAll wrong")
		return b, err
	}
	if resp.StatusCode != http.StatusOK {
		log.WithField("response http code wrong", log.Fields{"p.Url": p.Url, "err:": err, "resp": string(all)}).Errorf("Fetch wrong status code: %d", resp.StatusCode)
		//return b, status.Error(grpcError.ErrSystemBusy, "HttpRequest error")
		return b, err
	}
	return all, nil
}
